package cn.qu.v1.platform.inject;

import com.google.common.base.Strings;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

/**
 * Created by zh on 17/1/11.
 */
public class BeanKey {

    String beanName;
    Class<?> beanClass;

    public static BeanKey getKey(String beanName, Class<?> beanClass) {
        BeanKey key = new BeanKey();
        key.beanClass = beanClass;

        if (Strings.isNullOrEmpty(beanName)) {
            beanName = beanClass.getSimpleName();
            String c = Character.toString(beanName.charAt(0));
            key.beanName = beanName.replaceFirst(c, c.toLowerCase());
        } else {
            key.beanName = beanName;
        }
        return key;
    }

    public static BeanKey getKey(Class<?> beanClass) {
        return getKey(null, beanClass);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof BeanKey)) {
            return false;
        }
        BeanKey key = (BeanKey) obj;
        if (StringUtils.equals(key.beanName, this.beanName)) {
            return true;
        }
        if (key.beanClass == this.beanClass) {
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        int beancode = 0, namecode = 0;
        if (beanClass != null) {
            beancode = beanClass.getName().length();
        }
        if (beanName != null) {
            namecode = beanName.length();
        }

        return 17 * beancode + 17 * namecode;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}
